from django.shortcuts import render, redirect, HttpResponse
from web01 import models
from django.db.models import Q
from web01.forms import Articleform, ArticleDetailForm


def index(request):
    od_articles = models.Article.objects.order_by('-count_read')
    all_bigcategory = models.Bigcategory.objects.all()
    od_comments = models.Comment.objects.order_by('-create_time')
    pic1 = models.Pic.objects.first()
    pic2 = models.Pic.objects.all()[1]
    return render(request, 'index.html',
                  {'od_articles': od_articles, 'all_bigcategory': all_bigcategory, 'od_comments': od_comments,
                   'pic1': pic1, 'pic2': pic2})


def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        pwd = request.POST.get('password')
        user_obj = models.UserInfo.objects.filter(name=username).first()
        if user_obj and user_obj.password == pwd:
            request.session['is_login'] = 1
            request.session['user_pk'] = user_obj.pk
            return redirect('/index/')
    return render(request, 'login.html')


def article(request, num):
    article_obj = models.Article.objects.filter(pk=num).first()
    article_obj.count_read += 1
    article_obj.save()
    return render(request, 'article.html', {'article_obj': article_obj})


def article_list(request, bc_num, sc_num=None):
    bigcategories = models.Bigcategory.objects.filter(pk=bc_num)
    if sc_num:
        articles = models.Article.objects.filter(
            Q(category__bigcategory_id=bc_num) & Q(category__subcategory_id=sc_num), )
        return render(request, 'article_list.html', {'articles': articles, 'bigcategories': bigcategories})
    articles = models.Article.objects.filter(category__bigcategory_id=bc_num)
    return render(request, 'article_list.html', {'articles': articles, 'bigcategories': bigcategories})


def search(request):
    if request.method == 'POST':
        search_word = request.POST.get('word').strip()
        if search_word:
            s_articles = models.Article.objects.filter(
                Q(content__content__contains=search_word) | Q(title__contains=search_word))
            return render(request, 'search.html', {'s_articles': s_articles})
        else:
            return HttpResponse('搜索结果不能为空')
    return render(request, 'search.html')


def comment(request):
    content = request.POST.get('comment')
    article_id = request.META.get('HTTP_REFERER')[-1]
    models.Comment.objects.create(content=content, commentator_id=request.user_obj.pk, article_id=article_id)
    return redirect(request.META.get('HTTP_REFERER'))


def article_manage(request):
    all_articles = models.Article.objects.all()
    return render(request, 'article_manage.html', {'all_articles': all_articles})


def article_add(request):
    form_obj = Articleform()
    detailform_obj = ArticleDetailForm()
    if request.method == 'POST':
        detailform_obj = ArticleDetailForm(request.POST)
        form_obj = Articleform(request.POST)
        if detailform_obj.is_valid() and form_obj.is_valid():
            detail_obj = detailform_obj.save()
            form_obj.instance.content_id = detail_obj.pk
            form_obj.save()
            return redirect('/article_manage/')
    return render(request, 'article_add.html', {'form_obj': form_obj, 'detailform_obj': detailform_obj})


def article_del(request, pk):
    models.Article.objects.get(pk=pk).delete()
    return redirect('/article_manage/')


def article_edit(request, pk):
    obj = models.Article.objects.filter(pk=pk).first()
    form_obj = Articleform(instance=obj)
    article_detail_form_obj = ArticleDetailForm(instance=obj.content)
    if request.method == 'POST':
        form_obj = Articleform(request.POST, instance=obj)
        article_detail_form_obj = ArticleDetailForm(request.POST, instance=obj.content)
        if form_obj.is_valid() and article_detail_form_obj.is_valid():
            article_detail_form_obj.save()
            form_obj.save()
            return redirect('/article_manage/')

    return render(request, 'article_edit.html',
                  {'form_obj': form_obj, 'article_detail_form_obj': article_detail_form_obj})


def category_list(request):
    all_bcategories = models.Bigcategory.objects.all()
    return render(request, 'category_list.html', {'all_bcategories': all_bcategories})


def subcategory_add(request):
    if request.method == 'POST':
        title = request.POST.get('sc_title')
        models.Subcategory.objects.create(title=title)
        return redirect('/category_list/')
    return render(request, 'subcategory_add.html')


def bigcategory_add(request):
    if request.method == 'POST':
        title = request.POST.get('bc_title')
        models.Bigcategory.objects.create(title=title)
        return redirect('/category_list/')
    return render(request, 'bigcategory_add.html')


def category_del(request):
    del_id = request.GET.get('id')
    models.Bigcategory.objects.get(id=del_id).delete()
    return redirect('/category_list/')


def category_edit(request):
    if request.method == 'POST':
        edit_id = request.POST.get('id')
        edit_obj = models.Bigcategory.objects.get(id=edit_id)
        new_title = request.POST.get('bc_title')
        edit_obj.title = new_title

        subcategories = request.POST.getlist('sc_num')  # 新的子分类id列表

        # 减少了分类
        if edit_obj.categories.count() > len(subcategories):
            for i in edit_obj.categories.all():
                if i.subcategory_id in subcategories:
                    continue
                else:
                    i.delete()
        # 增加了分类
        elif edit_obj.categories.count() < len(subcategories):
            lis = []
            for i in edit_obj.categories.all():
                lis.append(i.subcategory_id)
            for s in subcategories:
                if s not in lis:
                    models.Category.objects.create(bigcategory=edit_obj, subcategory_id=s)
        return redirect('/category_list/')


    # 找出未被关联的子分类
    edit_id = request.GET.get('id')  # 大分类id
    edit_obj = models.Bigcategory.objects.get(id=edit_id)
    lis = []
    for i in models.Category.objects.values('subcategory_id'):
        lis.append(i['subcategory_id'])
    lis.remove(None)
    subcategories = models.Subcategory.objects.exclude(pk__in=lis)
    return render(request, 'category_edit.html', {'edit_obj': edit_obj, 'subcategories': subcategories})


def pic_change(request):
    if request.method == 'POST':
        uf = request.FILES.get("upload_file")
        with open('./static/images/index_img/index_pic2.jpg', "wb") as f:
            for i in uf.chunks():
                f.write(i)
        return HttpResponse('OK')
    pic1 = models.Pic.objects.first()
    pic2 = models.Pic.objects.all()[1]
    return render(request, 'pic_change.html', {'pic1': pic1, 'pic2': pic2})
